<?php

namespace Mouta\AmistateBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

use Mouta\AmistateBundle\Entity\Usuario;
use Mouta\AmistateBundle\Entity\Denuncias;
use Mouta\AmistateBundle\Entity\ImagenUsuario;
use Mouta\AmistateBundle\Entity\UsuarioRepository;
use Mouta\AmistateBundle\utils\SfFacebook;
use Mouta\AmistateBundle\utils\Recaptcha;



class GlobalController extends Controller
{
    public function headerAction()
    {
        $form = $this->container->get('fos_user.registration.form');
        $mostrarRegistro = true;
        if($this->getRequest()->getUri() == $this->generateUrl('fos_user_registration_register',array(),true)){
            $mostrarRegistro = false;
        }
        return $this->render('AmistateBundle:global:header.html.twig',array(
            'form' => $form->createView(),
            'mostrarRegistro'=>$mostrarRegistro,
        ));
    }
    
    public function loginExternoAction($param){
        $param = base64_decode($param);
        list($mail,$clave,$path) = explode('|', $param);
        $em = $this->get('doctrine')->getEntityManager();
        $usuario = $em->getRepository('AmistateBundle:Usuario')->findOneByEmail($mail);
        if(is_null($usuario))
            return $this->redirect( $this->generateUrl('_homepage'));
        else
        {
            if($usuario->getPassword() == $clave){
                $token = new UsernamePasswordToken($usuario, null, 'main', $usuario->getRoles());
                $this->get('security.context')->setToken($token);
                return $this->redirect( $this->generateUrl($path));
            }else
                return $this->redirect( $this->generateUrl('_homepage'));
        }
    }
    
    public function ContactoAction()
    {
        $valid = false;
        $respuesta = "";
        $form = $this->createFormBuilder()
            ->add('nombre','text')
            ->add('email','email')
            ->add('mensaje','textarea')
            ->add('captcha', 'captcha')
            ->getForm();
        if($this->getRequest()->getMethod() == "POST"){
            $form->bindRequest($this->getRequest());
            $respuesta = $form->get('mensaje')->getData();
            if($form->isValid()){
                $message = \Swift_Message::newInstance()
                    ->setSubject('Contacto de Amistate')
                    ->setFrom($form->get('email')->getData())
                    ->setTo('carlosdanielmou@gmail.com')
                    ->setCC('tricardocss@gmail.com')
                    ->setBody('Nombre: '.$form->get('nombre')->getData().'Email: ' .$form->get('email')->getData().'Mensaje: ' . $respuesta)
                ;
                $this->get('mailer')->send($message);
                $valid = true;
            }
        }
        return $this->render('AmistateBundle:global:contacto.html.twig',array(
            'form' => $form->createView(),
            'valid' => $valid,
            'respuesta' => $respuesta,
        ));
    }
    
    public function TerminosAction()
    {
        return $this->render('AmistateBundle:global:terminos.html.twig');
    }
    public function PrivacidadAction()
    {
        return $this->render('AmistateBundle:global:privacidad.html.twig');
    }

    public function atHeaderAction()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $usuarios = $em->getRepository('AmistateBundle:Usuario')->findUserAtHeader();
        return $this->render('AmistateBundle:global:atHeader.html.twig',array('usuarios'=>$usuarios));
    }
    
    public function loginHeaderAction()
    {
        $csrfToken = $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate');
        return $this->render('AmistateBundle:global:loginHeader.html.twig',array(
            'facebook_appid' => SfFacebook::APPID,
            'path' => $this->generateUrl('login_facebook'),
            'csrf_token' => $csrfToken,
        ));
    }
    public function menuAutenticadoAction()
    {
        $user = $this->get('security.context')->getToken()->getUser();
        $cantMensajes = $this->getDoctrine()->getEntityManager()->getRepository('AmistateBundle:Mensaje')->cantidadNoLeido($user->getId());
        $cantSolicitudes = $this->getDoctrine()->getEntityManager()->getRepository('AmistateBundle:Solicitud')->cantidadSolicitudesPendientes($user->getId());
        
        return $this->render('AmistateBundle:global:menuAutenticado.html.twig',array(
            'user'=> $user,
            'cantMensajes'=> $cantMensajes,
            'cantSolicitudes'=> $cantSolicitudes,
        ));
    }
    
    public function loginFacebookAction(){
        $facebook = SfFacebook::getFbConnecion();
        $user = $facebook->getUser();
        $fbme = null;
        if ($user) {
            try {
                // Proceed knowing you have a logged in user who's authenticated.
                $fbme = $facebook->api('/me');
            } catch (FacebookApiException $e) {
                return new Response(json_encode(array('valid'=>false,'openregistro'=>false,'mensaje'=>'Error al conectarse con Facebook')) );
            }
        }else{
            return new Response(json_encode(array('valid'=>false,'openregistro'=>false,'mensaje'=>'Error al conectarse con Facebook')) );
        }
        
        if(is_null($fbme))
        {
            return new Response(json_encode(array('valid'=>false,'openregistro'=>false,'mensaje'=>'Error al conectarse con Facebook')) );
        }

        $em = $this->get('doctrine')->getEntityManager();
        $usuario = $em->getRepository('AmistateBundle:Usuario')->findOneByEmail( $fbme["email"] );
        if($usuario)
        {
            $providerKey = $this->container->getParameter('fos_user.firewall_name');
            $token = new UsernamePasswordToken($usuario, null, $providerKey, $usuario->getRoles());
            $this->container->get('security.context')->setToken($token);
            return new Response(json_encode(array('valid'=>true)) );
        }else{
            return new Response(json_encode(array('valid'=>false,'openregistro'=>true,'mensaje'=>'Ustes no se encuentra registrado en Amistate')) );
        }
    }
    
    public function validateMailAction(){
        $request = $this->getRequest();
        if($request->getMethod()=='POST')
        {
            $email = "";
            if($this->get('security.context')->isGranted('ROLE_USER'))
            {
                $email = $this->get('security.context')->getToken()->getUser()->GetEmail();
            }
            $em = $this->get('doctrine')->getEntityManager();
            $r = $request->get('fos_user_registration_form');
            
            $usuario = $em->getRepository('AmistateBundle:Usuario')->findOneByEmail($r['email']);
            if(is_null($usuario))
                return new Response('true');
            else
                return new Response('false');
        }
        return new Response('false');
    }
}
